﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Microsoft.VisualStudio.Text;
using VSTranslator.Package;
using VSTranslator.Translation;

namespace VSTranslator.Adornment
{
	public partial class TranslationAdornment : UserControl
	{
		public TranslationRequest Request { get; set; }
		public ITrackingSpan Span { get; set; }
		public event EventHandler AdornmentClosed;		

		public TranslationAdornment(SnapshotSpan span, TranslationRequest request)
		{
			Span = span.Snapshot.CreateTrackingSpan(span, SpanTrackingMode.EdgeExclusive);
			Request = request;
			Request.TranslationComplete += request_TranslationComplete;
			InitializeComponent();      
                  
            switch(request.Translator.Name) {
                case "Google":
                    imgTranslator.Source = GetImage("google.png");
                    break;
                case "Bing":
                    imgTranslator.Source = GetImage("bing.png");
                    break;
            }
            imgTranslator.ToolTip = request.Translator.AccessibleName;
		}

        private BitmapImage GetImage(string name)
        {
            return new BitmapImage(new Uri("pack://application:,,,/TranslatorPackage;component/Images/" + name));
        }
		
		private void UserControl_Initialized(object sender, EventArgs e)
		{
			
		}

		private void RenderTranslation(TranslationResult translation)
		{
            lblDirection.Text = translation.SourceLanguage + " - " + translation.DestinationLanguage;
            if (translation.Sentences != null) {
                foreach (string s in translation.Sentences) { 
                    spContent.Children.Add(CreateItemControl(s));
                }
            }		

			foreach (DictionaryItem di in translation.DictionaryItems) {
				RenderDictionaryItem(di);
			}			
		}

		private void RenderDictionaryItem(DictionaryItem item)
		{
			spContent.Children.Add(new TextBlock {
				Text = item.Title, 
				FontWeight = FontWeights.Bold,
				Margin = new Thickness(4, 4, 2, 2),
				TextWrapping = TextWrapping.Wrap
			});

			foreach (string term in item.Terms) {
				UserControl c = CreateItemControl(term);
				c.Padding = new Thickness(6, 2, 2, 2);			
				spContent.Children.Add(c);
			}			
		}

		private UserControl CreateItemControl(string item)
		{
			TranslationItemControl c = new TranslationItemControl { Text = item };			
			c.Paste += OnPaste;
			return c;
		}

		void OnPaste(object sender, PasteEventArgs e)
		{
			ITextBuffer buffer = Span.TextBuffer;
			Span sp = Span.GetSpan(buffer.CurrentSnapshot);
			buffer.Replace(sp, e.Text);
		}

		private void RenderException(Exception ex)
		{
			lblDirection.Text = ex.Message;			
			lblDirection.Foreground = Brushes.Red;
		}

		private void OnAdornmentClosed()
		{
			if (AdornmentClosed != null)
				AdornmentClosed(this, EventArgs.Empty);
		}

		private void cmdClose_Click(object sender, RoutedEventArgs e)
		{
			OnAdornmentClosed();
		}

		private void cmdSettings_Click(object sender, RoutedEventArgs e)
		{
			Global.DTE.ExecuteCommand("Tools.Options", GuidList.OptionsPageGuid);
		}

		private void request_TranslationComplete(object sender, EventArgs e)
		{
			TranslationRequest request = (TranslationRequest)sender;
			Dispatcher.BeginInvoke(new Action(() =>
				{
					if (request.Result != null)
						RenderTranslation(request.Result);
					else
						RenderException(request.Exception);
				}));
		}

		public void DetachRequest()
		{
			Request.TranslationComplete -= request_TranslationComplete;
		}
	}
}
